﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using Bootstrap.Builders;
using DotLess.Services;

namespace Bootstrap.Services
{
    public class BootstrapBuildService : IBootstrapBuildService  {
        private readonly IBootstrapSettingsService _settings;
        private readonly IEnumerable<IBootstrapFeatureBuilder> _buildProviders;
        private readonly ILessCompilerService _lessCompiler;

        public BootstrapBuildService(
            IBootstrapSettingsService settings,
            IEnumerable<IBootstrapFeatureBuilder> buildProviders,
            ILessCompilerService lessCompiler) {
            _settings = settings;
            _buildProviders = buildProviders;
            _lessCompiler = lessCompiler;
        }

        public string Build() {
            var buildContext = new BuilderDescriptionContext();
            _buildProviders
                .ToList()
                .ForEach(
                    x => x.Describe(buildContext)
                );
            var builders =
                buildContext
                    .Builders
                    .ToDictionary(
                        x => x.Key,
                        x => x.Value(new BuilderDescriptor())
                    );
            var features =
                _settings
                    .EnabledFeatures()
                    .OrderBy(x => _settings.GetPosition(x.Name));
                    
            var template = new StringBuilder();
            foreach (var feature in features) {
                builders[feature.FeatureType]
                .Builder(_settings, feature)
                .ToList()
                .ForEach(x => template.Append(x));
            }

            var fullTemplate = template.ToString();

            var result = _lessCompiler.CompileString(fullTemplate, "~/themes/Bootstrap/Styles");
            return result;
        }

        public bool BuildToFile() {
            var folder = HostingEnvironment.MapPath("~/Themes/Bootstrap/Styles");
            var path = folder + "\\bootstrap.css";

            var writer = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write));
            writer.Write(Build());
            writer.Flush();
            writer.Close();

            return true;
        }

    }
}

